<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ref, reactive, toRaw, onMounted, onBeforeUnmount } from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { initRouter } from "@/router/utils";
import { getCaptchaBase64 } from "@/api/Common";
import { IsHttpImg } from "@/utils/imgtool";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  name: "",
  password: "",
  captchacode: "",
  captchaid: "",
  captchaurl: ""
});
//登录事件
const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      useUserStoreHook()
        .loginByUsername(toRaw(ruleForm))
        .then(res => {
          if (res.code == 1) {
            //设置头像
            if (res.data.data.photo !== null && res.data.data.photo !== "") {
              const userphoto = IsHttpImg(res.data.data.photo);
              window.localStorage.setItem("userphoto", userphoto);
            } else {
              window.localStorage.setItem(
                "userphoto",
                "/assets/img/headportrait.jpg"
              );
            }
            // 获取后端路由
            initRouter().then(() => {
              router.push("/");
              message("登录成功", { type: "success" });
            });
          } else {
            refreshtCaptcha(); //刷新验证码
            loading.value = false;
            message(res.msg, { type: "error" });
          }
        })
        .catch(err => {
          console.log("login/index 登录失败");
          console.log(err);
          refreshtCaptcha(); //刷新验证码
          loading.value = false;
          message("登录失败", { type: "error" });
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});

//请求验证码 refreshtCaptcha
function getCaptcha(capkey: string) {
  getCaptchaBase64(capkey)
    .then(res => {
      if (res.code !== 1) {
        message("获取验证码失败请控制台查看日志", { type: "error" });
      } else {
        ruleForm.captchaurl = res.data.base64;
      }
    })
    .catch(err => {
      console.log(err);
      message("获取验证码失败请控制台查看日志", { type: "error" });
    });
}
refreshtCaptcha();
//刷新验证码
function refreshtCaptcha() {
  ruleForm.captchaid = Math.random().toString(36).substring(2);
  getCaptcha(ruleForm.captchaid);
}
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <el-form ref="ruleFormRef" :model="ruleForm" size="large">
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="name"
              >
                <el-input
                  clearable
                  v-model="ruleForm.name"
                  placeholder="账号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item
                prop="password"
                :rules="[
                  {
                    required: true,
                    message: '请输入密码',
                    trigger: 'blur'
                  }
                ]"
              >
                <el-input
                  clearable
                  show-password
                  v-model="ruleForm.password"
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>
            <Motion :delay="150">
              <el-form-item
                prop="captchacode"
                :rules="[
                  {
                    required: true,
                    message: '请输入验证码',
                    trigger: 'blur'
                  }
                ]"
              >
                <el-input
                  clearable
                  placeholder="验证码"
                  v-model="ruleForm.captchacode"
                  :prefix-icon="useRenderIcon('ri:shield-keyhole-line')"
                  ><template v-slot:append>
                    <img
                      :src="'data:image/gif;base64,' + ruleForm.captchaurl"
                      @click="refreshtCaptcha"
                    /> </template
                ></el-input>
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
